package com.ttai.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ttai.R;
import com.ttai.dagger.componet.activity.DaggerLoginIdComponet;
import com.ttai.dagger.module.activity.LoginIdPresenterModule;
import com.ttai.presenter.activity.AppNamePresenter;
import com.ttai.presenter.activity.HomePresrenter;
import com.ttai.presenter.activity.InsertIdAcountPresenter;
import com.ttai.presenter.activity.LoginIdPresenter;
import com.ttai.ui.adapter.LoginIdRecycleViewAdapter;
import com.ttai.ui.base.BaseActivity;
import com.ttai.untils.Constant;
import com.ttai.untils.ItemClickSupport;
import com.ttai.untils.ShareCodeUtil;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yzq.zxinglibrary.android.CaptureActivity;

import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginId extends BaseActivity {
    @Bind(R.id.ib_addidacount)
    Button ibAddidacount;
    @Bind(R.id.rv_idlist)
    RecyclerView rvIdlist;

    @Inject
    LoginIdPresenter loginIdPresenter;

    InsertIdAcountPresenter insertIdAcountPresenter;

    LoginIdRecycleViewAdapter loginIdRecycleViewAdapter;
    @Bind(R.id.btn_saomiao)
    Button btnSaomiao;

    private AppNamePresenter appNamePresenter;

    public String appName;
    public String appAcount;
    private String phonenumber;
    private int REQUEST_CODE_SCAN = 111;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginid);

        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView barTitle = (TextView)findViewById(R.id.barTitle);
        barTitle.setText("托管登录身份验证");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        ButterKnife.bind(this);
        setComponet();

        insertIdAcountPresenter = new InsertIdAcountPresenter(this);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);

        appNamePresenter = new AppNamePresenter(this);
        appNamePresenter.getAppName();


        loginIdRecycleViewAdapter = new LoginIdRecycleViewAdapter(this);
        rvIdlist.setAdapter(loginIdRecycleViewAdapter);
//        rvIdlist.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        rvIdlist.setLayoutManager(new GridLayoutManager(this, 3));

//        loginIdPresenter.getData();
        insertIdAcountPresenter.storeIdAcount(Constant.getToken());

        ItemClickSupport.addTo(rvIdlist).setOnItemLongClickListener(new ItemClickSupport.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClicked(RecyclerView recyclerView, final int position, View v) {
                appName = insertIdAcountPresenter.getList().get(position).getId_name();
                appAcount = insertIdAcountPresenter.getList().get(position).getId_acountnumber();
                AlertDialog.Builder builder = new AlertDialog.Builder(LoginId.this);
                builder.setMessage("确定删除?");
                builder.setTitle("提示");

                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (insertIdAcountPresenter.getList().remove(position) != null) {

                            String token = Constant.getToken();
                            if (HomePresrenter.myPhone == null || HomePresrenter.myPhone.isEmpty()) {
                                if (Register.phonenumber == null || Register.phonenumber.isEmpty()) {
                                    phonenumber = EnterPage.enterphonenumber;
                                } else {
                                    phonenumber = Register.phonenumber;
                                }
                            } else {
                                phonenumber = HomePresrenter.myPhone;
                            }
                            loginIdPresenter.idDelete(token, "1", appAcount);
                        } else {
                        }
//                        Toast.makeText(getBaseContext(), "删除成功", Toast.LENGTH_SHORT).show();
                    }
                });

                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.create().show();
                return true;
            }
        });

        ItemClickSupport.addTo(rvIdlist).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {

            private String acountlogo;

            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                appName = insertIdAcountPresenter.getList().get(position).getId_name();
                acountlogo = insertIdAcountPresenter.getList().get(position).getAcountnumberlogo();
                appAcount = insertIdAcountPresenter.getList().get(position).getId_acountnumber();
                Intent intent = new Intent();
                intent.putExtra("idname", appName);
                intent.putExtra("acountnumberlogo", acountlogo);
                intent.putExtra("accountnumber", appAcount);
                intent.setClass(LoginId.this, IdItem.class);
                startActivity(intent);
                Toast.makeText(LoginId.this, appName, Toast.LENGTH_SHORT).show();
            }
        });


    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case android.R.id.home:
//                finish();
//                break;
//        }
//        return super.onOptionsItemSelected(item);
//    }

    @Override
    public void next(View view) {

    }

    @Override
    public void pre(View view) {
        finish();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void setComponet() {
        DaggerLoginIdComponet.builder()
                .loginIdPresenterModule(new LoginIdPresenterModule(this))
                .build()
                .in(this);
    }

    public LoginIdRecycleViewAdapter getLoginIdRecycleViewAdapter() {
        return loginIdRecycleViewAdapter;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT);
                try {
                    String context = Constant.getFromBASE64(content);
                    System.out.println("context" + context);
                    List<String> result = Arrays.asList(context.split(","));
                    String qrId = result.get(0);
                    String appId = result.get(1);
                    System.out.println("qrId" + qrId + " appId" + appId);
                    System.out.println("flag:" + ShareCodeUtil.codeToId(appId));
//                    qrLoginPresenter.qrLogin();
                    Intent intent = new Intent(this, ChooseId.class);
                    intent.putExtra("qrId", qrId);
                    intent.putExtra("appId", appId);
                    startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(this, "无效二维码", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @OnClick({R.id.btn_saomiao, R.id.ib_addidacount})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_saomiao:
                AndPermission.with(this)
                        .permission(com.yanzhenjie.permission.Permission.CAMERA, com.yanzhenjie.permission.Permission.READ_EXTERNAL_STORAGE)
                        .onGranted(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Intent intent = new Intent(LoginId.this, CaptureActivity.class);
                                /*ZxingConfig是配置类
                                 *可以设置是否显示底部布局，闪光灯，相册，
                                 * 是否播放提示音  震动
                                 * 设置扫描框颜色等
                                 * 也可以不传这个参数
                                 * */
//                                ZxingConfig config = new ZxingConfig();
//                                config.setPlayBeep(false);//是否播放扫描声音 默认为true
//                                config.setShake(false);//是否震动  默认为true
//                                config.setDecodeBarCode(false);//是否扫描条形码 默认为true
//                                config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
//                                config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
//                                config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
//                                config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
//                                intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                                startActivityForResult(intent, REQUEST_CODE_SCAN);
                            }
                        })
                        .onDenied(new Action() {
                            @Override
                            public void onAction(List<String> permissions) {
                                Uri packageURI = Uri.parse("package:" + getPackageName());
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                startActivity(intent);

                                Toast.makeText(LoginId.this, "没有权限无法扫描呦", Toast.LENGTH_LONG).show();
                            }
                        }).start();

                break;
            case R.id.ib_addidacount:
                Intent intent = new Intent();
                intent.setClass(LoginId.this, AddIdAcount.class);
                startActivity(intent);
                break;
        }

//    @OnClick(R.id.ib_addidacount)
//    public void onViewClicked() {
//        Intent intent=new Intent();
//        intent.setClass(LoginId.this,AddIdAcount.class);
//        startActivity(intent);
//    }
    }
}
